import { Inject, Provide } from '@midwayjs/decorator';
import { Context } from '@midwayjs/koa';
import { Repository } from 'typeorm';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import http = require('urllib');
import * as cheerio from 'cheerio';
import { NewzfCommonService } from './common';
import { UserEntity } from '../../entity/user';
const { StartTime, EndTime } = require('../../../../comm/courseTime');

/**
 * API服务
 */
@Provide()
export class NewzfApiService extends BaseService {
    @Inject()
    ctx: Context;

    @Inject()
    common: NewzfCommonService;

    @InjectEntityModel(UserEntity)
    userEntity: Repository<UserEntity>;

    /**
     * 用户登录
     * @param id 学校ID
     * @param url 学校URL
     * @param loginType 登录类型
     * @param username 用户名
     * @param password 密码
     */
    async login(id, url, loginType, username, password) {
        try {
            const { success, message, cookie } = await this.common.get_cookie(this.ctx.user.userId, url, loginType, username, password, false);
            if (!success) return { success, message, data: [] };
            const { status, data } = await http.request(`${url}/xsxxxggl/xsgrxxwh_cxXsgrxx.html?gnmkdm=N100801&layout=default&su=${username}`, {
                method: 'GET',
                timeout: 10000,
                headers: {
                    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
                    'Accept-Encoding': 'gzip, deflate, br',
                    'Accept-Language': 'zh-CN,zh;q=0.9',
                    'Connection': 'keep-alive',
                    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
                    'Cookie': `${cookie}`,
                    'Origin': `${url}`,
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36'
                }
            });
            if (status !== 200) return { success: false, message: '服务器异常', data: [] };
            const $ = cheerio.load(data);
            const info = {
                name: $('#col_xm').text().trim(),       // 姓名
                sex: $('#col_xbm').text().trim(),       // 性别
                idCard: $('#col_zjhm').text().trim(),   // 身份证
                nation: $('#col_mzm').text().trim(),    // 民族
                birthday: $('#col_csrq').text().trim(), // 生日
                college: $('#col_jg_id').text().trim(), // 学院
                major: $('#col_zyh_id').text().trim(),  // 专业
                class: $('#col_bh_id').text().trim()    // 班级
            };
            const { affected } = await this.userEntity.update({ id: this.ctx.user.userId }, {
                username,
                password,
                schoolId: id,
                name: info.name,
                sex: info.sex == "男" ? 1 : 2,
                idCard: info.idCard,
                nation: info.nation,
                birthday: info.birthday,
                college: info.college,
                major: info.major,
                class: info.class
            });
            if (affected <= 0) {
                return {
                    success: false,
                    message: '登录失败',
                    data: []
                };
            }
            return {
                success: true,
                message: '登录成功',
                data: []
            };
        } catch (error) {
            return {
                success: false,
                message: '服务器异常',
                data: []
            };
        }
    }

    /**
     * 课表查询
     * @param url URL地址
     * @param loginType 登录类型
     * @param username 用户名
     * @param password 密码
     * @param year 年份
     * @param term 学期
     */
    async get_course(url, loginType, username, password, year, term) {
        try {
            const { success, message, cookie } = await this.common.get_cookie(this.ctx.user.userId, url, loginType, username, password);
            if (!success) return { success, message, data: [] };
            const { status, data } = await http.request(`${url}/kbcx/xskbcx_cxXsgrkb.html?gnmkdm=N2151&su=${username}`, {
                method: 'POST',
                timeout: 10000,
                headers: {
                    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
                    'Accept-Encoding': 'gzip, deflate, br',
                    'Accept-Language': 'zh-CN,zh;q=0.9',
                    'Connection': 'keep-alive',
                    'Content-Type': "application/x-www-form-urlencoded;charset=utf-8",
                    'Cookie': `${cookie}`,
                    'Origin': `${url}`,
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36'
                },
                data: {
                    'xnm': year,
                    'xqm': term == 2 ? 12 : 3,
                    'kzlx': 'ck'
                }
            });
            if (status !== 200) return { success: false, message: '服务器异常' };
            const response_data = JSON.parse(data.toString());
            const practiceCourseList = response_data.sjkList;
            const courseList = response_data.kbList;
            const parcticeCourse = practiceCourseList.map(currentValue => {
                return {
                    info: currentValue.sjkcgs
                }
            });
            const colorItem = [ 
                "#FF9966",
                "#66CC99",
                "#FF99CC",
                "#FF6666",
                "#99CCFF",
                "#66CCFF",
                "#99CCCC",
                "#6E27BA",
                "#4C3FAE",
                "#3465CC",
                "#28A1BA",
                "#24BA97",
                "#1DC069",
                "#28B93D",
                "#CC5A36",
                "#743F23"
            ];
            const course = courseList.map((currentValue, index) => {
                return {
                    id: currentValue.kch_id,            // 课程ID
                    name: currentValue.kcmc,            // 课程名称
                    address: currentValue.cdmc,         // 上课地点
                    week: currentValue.zcd,             // 周次
                    day: currentValue.xqj,              // 星期
                    period: currentValue.jcs,           // 节次
                    section: currentValue.jc,           // 节数
                    credit: currentValue.xf,            // 学分
                    hours: currentValue.kczxs,          // 总学时
                    assessment: currentValue.khfsmc,    // 考核方式
                    campus: currentValue.xqmc,          // 校区名称
                    weekText: currentValue.zcd,         // 周次文本
                    teacher: currentValue.xm,           // 教师姓名
                    color: colorItem[index]             // 背景颜色
                }
            });
            for (let i = 0; i < course.length; i++) {
                let item = course[i];
                let weeks = [];
                let sections = [];
                let weekArr = item.week.split(',');
                const courseArr = item.period.split('-');
                const startTime = StartTime(courseArr[0]);
                const endTime = EndTime(courseArr[1]);
                for (let j = 0; j < weekArr.length; j++) {
                    const str = weekArr[j];
                    const arr = str.match(/[0-9]+/g);
                    if (str.length <= 3) {
                        weeks.push(parseInt(arr));
                    } else {
                        const start = parseInt(arr[0]);
                        const end = parseInt(arr[1]);
                        for (let w = start; w <= end; w++) {
                            weeks.push(w);
                        }
                    }
                }
                for (let s = 0; s < courseArr.length; s++) {
                    sections.push(parseInt(courseArr[s]));
                }
                item.weeks = weeks;
                item.sections = sections;
                item.startTime = startTime;
                item.endTime = endTime;
                item.day = parseInt(item.day);
                delete item.week;
                delete item.period;
            };
            return {
                success: true,
                message: "查询成功",
                data: {
                    parcticeCourse,
                    course
                }
            };
        } catch (error) {
            return {
                success: false,
                message: '服务器异常',
                data: []
            };
        }
    }

    /**
     * 成绩查询
     * @param url URL地址
     * @param loginType 登录类型
     * @param username 用户名
     * @param password 密码
     * @param year 年份
     * @param term 学期
     */
    async get_grade(url, loginType, username, password, year, term) {
        try {
            const { success, message, cookie } = await this.common.get_cookie(this.ctx.user.userId, url, loginType, username, password);
            if (!success) return { success, message, data: [] };
            const { status, data } = await http.request(`${url}/cjcx/cjcx_cxXsgrcj.html?doType=query&gnmkdm=N305005&su=${username}`, {
                method: 'POST',
                timeout: 10000,
                headers: {
                    'Accept': 'application/json, text/javascript, */*; q=0.01',
                    'Accept-Encoding': 'gzip, deflate, br',
                    'Accept-Language': 'zh-CN,zh;q=0.9',
                    'Connection': 'keep-alive',
                    'Content-Type': "application/x-www-form-urlencoded;charset=utf-8",
                    'Cookie': `${cookie}`,
                    'Origin': `${url}`,
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36'
                },
                data: {
                    'xnm': year,
                    'xqm': term == 2 ? 12 : 3,
                    '_search': false,
                    'nd': new Date().getTime(),
                    'queryModel.showCount': 20,
                    'queryModel.currentPage': 1,
                    'queryModel.sortName': '',
                    'queryModel.sortOrder': 'asc',
                    'time': 0
                }
            });
            if (status !== 200) return { success: false, message: '服务器异常' };
            const response_data = JSON.parse(data.toString());
            const scoreList = response_data.items;
            const score = scoreList.map(currentValue => {
                return {
                    name: currentValue.kcmc,    // 课程名称
                    score: currentValue.bfzcj,  // 成绩
                    teacher: currentValue.jsxm, // 教师姓名
                    credit: currentValue.xf,    // 学分
                    courseId: currentValue.kch, // 课程号
                };
            });
            return {
                success: true,
                message: "查询成功",
                data: score
            };
        } catch (error) {
            return {
                success: false,
                message: '服务器异常',
                data: []
            };
        }
    }

    /**
     * 课程通知查询
     * @param url URL地址
     * @param loginType 登录类型
     * @param username 用户名
     * @param password 密码
     * @param read 是否已读
     */
    async get_course_notify(url, loginType, username, password, read) {
        try {
            const { success, message, cookie } = await this.common.get_cookie(this.ctx.user.userId, url, loginType, username, password);
            if (!success) return { success, message, data: [] };
            const { status, data } = await http.request(`${url}/xtgl/index_cxDbsy.html?doType=query`, {
                method: 'POST',
                timeout: 10000,
                headers: {
                    'Accept': 'application/json, text/javascript, */*; q=0.01',
                    'Accept-Encoding': 'gzip, deflate, br',
                    'Accept-Language': 'zh-CN,zh;q=0.9',
                    'Connection': 'keep-alive',
                    'Content-Type': "application/x-www-form-urlencoded;charset=utf-8",
                    'Cookie': `${cookie}`,
                    'Origin': `${url}`,
                    'Referer': `${url}/xtgl/index_initMenu.html`,
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/101.0.4951.54 Safari/537.36'
                },
                data: {
                    'sfyy': read ? 2 : 1,
                    'flag': 1,
                    '_search': false,
                    'nd': new Date().getTime(),
                    'queryModel.showCount': 100,
                    'queryModel.currentPage': 1,
                    'queryModel.sortName': 'cjsj',
                    'queryModel.sortOrder': 'desc',
                    'time': 0
                }
            });
            if (status !== 200) return { success: false, message: '服务器异常' };
            const response_data = JSON.parse(data.toString());
            const course_notify = response_data.items.map(noticeValue => {
                return {
                    date: noticeValue.cjsj.substring(0, 10),    // 日期
                    time: noticeValue.cjsj.substring(11, 16),   // 时间
                    title: noticeValue.xxbtjc,                  // 通知标题
                    news: noticeValue.xxnr,                     // 通知内容
                    notifyId: noticeValue.id                    // 通知ID
                }
            });
            return {
                success: true,
                message: "查询成功",
                data: course_notify
            };
        } catch (error) {
            return {
                success: false,
                message: '服务器异常',
                data: []
            };
        }
    }

    /**
     * 阅读课程通知
     * @param url URL地址
     * @param loginType 登录类型
     * @param username 用户名
     * @param password 密码
     * @param notifyId 通知ID
     */
    async read_notify(url, loginType, username, password, notifyId) {
        try {
            const { success, message, cookie } = await this.common.get_cookie(this.ctx.user.userId, url, loginType, username, password);
            if (!success) return { success, message, data: null };
            const { status } = await http.request(`${url}/xtgl/index_cxXxdlztgx.html`, {
                method: 'POST',
                timeout: 10000,
                headers: {
                    'Accept': 'application/json, text/javascript, */*; q=0.01',
                    'Accept-Encoding': 'gzip, deflate, br',
                    'Accept-Language': 'zh-CN,zh;q=0.9',
                    'Connection': 'keep-alive',
                    'Content-Type': "application/x-www-form-urlencoded;charset=utf-8",
                    'Cookie': `${cookie}`,
                    'Origin': `${url}`,
                    'Referer': `${url}/xtgl/index_initMenu.html`,
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/101.0.4951.54 Safari/537.36'
                },
                data: {
                    'zjxx': notifyId
                }
            });
            if (status !== 200) return { success: false, message: '服务器异常' };
            return {
                success: true,
                message: "操作成功",
                data: []
            };
        } catch (error) {
            return {
                success: false,
                message: '服务器异常',
                data: []
            };
        }
    }

    /**
     * 考试信息查询
     * @param url URL地址
     * @param loginType 登录类型
     * @param username 用户名
     * @param password 密码
     * @param year 年份
     * @param term 学期
     */
    async get_exam(url, loginType, username, password, year, term) {
        try {
            const { success, message, cookie } = await this.common.get_cookie(this.ctx.user.userId, url, loginType, username, password);
            if (!success) return { success, message, data: [] };
            const { status, data } = await http.request(`${url}/kwgl/kscx_cxXsksxxIndex.html?doType=query&gnmkdm=N358105&su=${username}`, {
                method: 'POST',
                timeout: 10000,
                headers: {
                    'Accept': 'application/json, text/javascript, */*; q=0.01',
                    'Accept-Encoding': 'gzip, deflate, br',
                    'Accept-Language': 'zh-CN,zh;q=0.9',
                    'Connection': 'keep-alive',
                    'Content-Type': "application/x-www-form-urlencoded;charset=utf-8",
                    'Cookie': `${cookie}`,
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36'
                },
                data: {
                    'xnm': year,
                    'xqm': term == 2 ? 12 : 3,
                    'ksmcdmb_id': '',
                    'kch': '',
                    'kc': '',
                    'ksrq': '',
                    'kkbm_id': '',
                    '_search': false,
                    'nd': new Date().getTime(),
                    'queryModel.showCount': 20,
                    'queryModel.currentPage': 1,
                    'queryModel.sortName': '',
                    'queryModel.sortOrder': 'asc',
                    'time': 0
                }
            });
            if (status !== 200) return { success: false, message: '服务器异常' };
            try {
                const response_data = JSON.parse(data.toString());
                const exam = response_data.items.map(examValue => {
                    return {
                        name: examValue.kcmc,
                        date: examValue.kssj.match(/\d*[-]\d*[-]\d*/g)[0] || null,
                        time: examValue.kssj.match(/\d*[:]\d*[-]\d*[:]\d*/g)[0] || null,
                        address: examValue.cdmc,
                        teacher: examValue.jsxx.match(/[\u4e00-\u9fa5]/g).join(""),
                        tyte: examValue.ksfs
                    };
                })
                return {
                    success: true,
                    message: "查询成功",
                    data: exam
                };
            } catch (error) {
                return {
                    success: true,
                    message: "查询成功",
                    data: []
                };
            }
        } catch (error) {
            return {
                success: false,
                message: '服务器异常',
                data: []
            };
        }
    }
}